<template>
  <div class="container">
    <div class="menuBar">
      <el-button type="primary" round size="small" @click="menuContainerShow(0)"
        >开始</el-button
      >
      <el-button type="primary" round size="small" @click="menuContainerShow(1)"
        >工具</el-button
      >
      <el-button type="primary" round size="small" @click="menuContainerShow(2)"
        >帮助</el-button
      >
    </div>
    <div class="menuContainer" v-show="menuContainertag1">
      <div class="imgcontainer" style="margin-left: 20px">
        <img class="img" src="../assets/icon/new/文件.svg" alt="" />
        <div class="textcontainer">打开</div>
      </div>
      <div class="imgcontainer">
        <img class="img" src="../assets/icon/new/存储.svg" alt="" />
        <div class="textcontainer">保存</div>
      </div>
      <div class="imgcontainer" @click="watershedIniTag = !watershedIniTag">
        <img class="img" src="../assets/icon/new/初始化.svg" alt="" />
        <div class="textcontainer">初始化</div>
      </div>
    </div>
    <div class="menuContainer" v-show="menuContainertag2">
      <div
        class="imgcontainer"
        style="margin-left: 20px"
        @click="cursor_pointer = true"
      >
        <img class="img" src="../assets/icon/new/漫游.svg" alt="" />
        <div class="textcontainer">漫游</div>
      </div>

      <div class="imgcontainer" @click="cursor_pointer = false">
        <img class="img" src="../assets/icon/new/选择.svg" alt="" />
        <div class="textcontainer">选择</div>
      </div>

      <div class="imgcontainer" @click="drawPoint">
        <img class="img" src="../assets/icon/new/圆点.svg" alt="" />
        <div class="textcontainer">点</div>
      </div>

      <div class="imgcontainer" @click="drawPolygon">
        <img class="img" src="../assets/icon/new/多边形.svg" alt="" />
        <div class="textcontainer">多边形</div>
      </div>

      <div class="imgcontainer" @click="drawBox">
        <img class="img" src="../assets/icon/new/矩形.svg" alt="" />
        <div class="textcontainer">矩形</div>
      </div>
      <!-- <div class="imgcontainer" @click="addDoc">
        <img class="img" src="../assets/icon/new/添加数据表.svg" alt="" />
        <div class="textcontainer">添加</div>
      </div> -->
      <div
        class="imgcontainer"
        @click="addOutletTag = !addOutletTag"
        style="width: fit-content"
      >
        <img class="img" src="../assets/icon/new/添加点.svg" alt="" />
        <div class="textcontainer">添加出水口</div>
      </div>
      <div class="imgcontainer" @click="rollBack">
        <img class="img" src="../assets/icon/new/回退.svg" alt="" />
        <div class="textcontainer">撤回</div>
      </div>
    </div>
    <div class="menuContainer" v-show="menuContainertag3">
      <div class="imgcontainer" style="margin-left: 20px">
        <img class="img" src="../assets/icon/new/帮助.svg" alt="" />
        <div class="textcontainer">帮助</div>
      </div>
      <div class="imgcontainer">
        <img class="img" src="../assets/icon/new/关于.svg" alt="" />
        <div class="textcontainer">关于</div>
      </div>
    </div>
    <div id="mapDiv" class="mapDiv" v-bind:class="{ pointer: cursor_pointer }">
      <div class="leftmenue">
        <el-row>
          <el-card
            shadow="always"
            style="
              background-color: rgba(76, 118, 199, 0.9);
              color: white;
              border: none;
            "
            body-style="padding: 10px;text-align: center;"
          >
            <span class="layertitle">图层信息</span>
          </el-card>
        </el-row>
        <el-row>
          <el-card
            shadow="always"
            style="background-color: rgba(237, 239, 239, 0.9)"
            body-style="padding: 10px;"
          >
            <el-tree
              :data="leftmenudata"
              @check-change="layertreeCheckChange"
              show-checkbox
              :highlight-current="true"
              node-key="id"
              :default-expanded-keys="[1, 2, 3]"
              ref="layertree"
              style="background-color: rgba(255, 255, 255, 0)"
            >
            </el-tree>
          </el-card>
        </el-row>
      </div>
      <div class="lonlatcontainer">
        <span>{{ lonlat }}</span>
      </div>
      <div class="box-card" v-drag v-if="watershedIniTag">
        <div class="cardTitle">
          <img src="../assets/icon/new/初始化1.svg" />
          <span class="titleText">流域初始化</span>
        </div>
        <div class="cardContent">
          <div class="content1">
            <label class="lable">最小坐标：</label>
            <div class="input">
              <el-input
                v-model="watershedMinLonLat"
                size="small"
                placeholder="MinLon, MinLat"
                clearable
              >
              </el-input>
            </div>
          </div>
          <div class="content2">
            <label class="lable">最大坐标：</label>
            <div class="input">
              <el-input
                v-model="watershedMaxLonLat"
                size="small"
                placeholder="MaxLon, MaxLat"
                clearable
              >
              </el-input>
            </div>
          </div>
          <div class="content3">
            <label class="lable">出水口坐标：</label>
            <div class="input">
              <el-input
                v-model="outletLonLat"
                size="small"
                placeholder="Lon,Lat"
                clearable
              >
              </el-input>
            </div>
          </div>
          <div class="content4">
            <div class="content4_1" v-show="basinInitialLoadingTag">
              <span class="el-icon-loading loading"></span>
              <span class="loadText">计算中...</span>
            </div>
            <div class="content4_2">
              <el-button
                size="medium"
                @click="basinInitial"
                :disabled="basinInitialbtndisableTag"
                >确定</el-button
              >
              <el-button
                size="medium"
                @click="watershedIniTag = !watershedIniTag"
                >取消</el-button
              >
            </div>
          </div>
        </div>
      </div>

      <div class="box-card" v-drag v-if="addOutletTag">
        <div class="cardTitle">
          <img src="../assets/icon/new/control_point.svg" alt="" />
          <span class="titleText">添加水文站信息</span>
        </div>
        <div class="cardContent">
          <div class="content1">
            <label class="lable">流域名称：</label>
            <div class="input">
              <el-input
                v-model="watershedMinLonLat"
                size="small"
                placeholder="水文站以上流域的名称"
                clearable
              >
              </el-input>
            </div>
          </div>
          <div class="content2">
            <label class="lable">水文站名称：</label>
            <div class="input">
              <el-input
                v-model="watershedMaxLonLat"
                size="small"
                placeholder="水文站点名称"
                clearable
              >
              </el-input>
            </div>
          </div>
          <div class="content3">
            <label class="lable">水文站坐标：</label>
            <div class="input">
              <el-input
                v-model="outlatstationlonlat"
                size="small"
                placeholder="Lon,Lat"
                clearable
              >
              </el-input>
              <img
                class="pickupicon"
                src="../assets/icon/new/拾取.svg"
                alt=""
                @click="drawPoint"
              />
            </div>
          </div>
          <div class="content4">
            <div class="content4_1" v-show="addOutletLoadingTag">
              <span class="el-icon-loading loading"></span>
              <span class="loadText">计算中...</span>
            </div>
            <div class="content4_2">
              <el-button
                size="medium"
                @click="DivideSubBasin"
                :disabled="addOutletbtndisableTag"
                >子流域划分
              </el-button>
              <el-button size="medium" @click="addOutletTag = !addOutletTag">
                取消
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import * as echarts from "echarts";
import "ol/ol.css";
import { Feature, Map, View } from "ol";
import { Vector as VectorLayer, Tile as TileLayer, Image } from "ol/layer";
import OverviewMap from "ol/control/OverviewMap";
import proj, { get } from "ol/proj";
import Draw, { createBox, createRegularPolygon } from "ol/interaction/Draw";
import { Snap, DoubleClickZoom } from "ol/interaction";
import { boundingExtent } from "ol/extent";
import {
  TileWMS as TileWMSSource,
  Vector as VectorSource,
  XYZ,
  TileImage,
  ImageWMS,
  OSM,
} from "ol/source";
import GeoJSON from "ol/format/GeoJSON";
import loadingstrategy from "ol/loadingstrategy";
import tilegrid from "ol/tilegrid";
import { format } from "ol/coordinate";
import "../assets/css/mainWindow.css";
import { Circle as CircleStyle, Fill, Stroke, Style } from "ol/style";
import drag from "../assets/js/drag.js";
import swal from "sweetalert";

export default {
  data() {
    return {
      leftmenudata: [
        {
          id: 1,
          label: "背景图层",
          children: [
            {
              id: 1.1,
              label: "天地图矢量图层",
            },
            {
              id: 1.2,
              label: "天地图影像图层",
            },
            {
              id: 1.3,
              label: "天地图地形图层",
            },
          ],
        },
        {
          id: 2,
          label: "流域图层",
          children: [
            {
              id: 2.1,
              label: "河网",
            },
            {
              id: 2.2,
              label: "流域边界",
            },
            {
              id: 2.3,
              label: "流域水系",
            },
            {
              id: 2.4,
              label: "子流域边界",
            },
            {
              id: 2.5,
              label: "子流域",
            },
          ],
        },
        {
          id: 3,
          label: "水文站网",
          children: [
            {
              id: 3.1,
              label: "水文",
            },
            {
              id: 3.2,
              label: "水位",
            },
            {
              id: 3.3,
              label: "气象",
            },
            {
              id: 3.4,
              label: "泥沙",
            },
          ],
        },
        {
          id: 4,
          label: "其他",
          children: [
            // {
            //   id: 3 - 1,
            //   label: "其他",
            // },
          ],
        },
      ],
      loading: true,
      menuContainertag1: true,
      menuContainertag2: false,
      menuContainertag3: false,
      map: null,
      watershedIniTag: false, //流域初始化配置框显示影藏
      addOutletTag: false, //添加出水口配置框显示影藏

      divideSubBasinTag: false,
      addOutletLoadingTag: false, //加载图标显示影藏
      addOutletbtndisableTag: false,

      basinInitialTag: false,
      basinInitialLoadingTag: false, //加载图标显示影藏
      basinInitialbtndisableTag: false,
      watershedMaxLonLat: "",
      watershedMinLonLat: "",
      outletLonLat: "",
      checkedId: "1.1", //最后拿到的唯一选择的id值
      backLayersId: 1.1, //最后拿到的背景图层节点的id值
      lonlat: "[ 666.00000000, 66.00000000 ]",
      outlatstationlonlat: "",
      tdtMap_vecLayer: null, //天地图矢量图层
      tdtMap_terLayer: null, // 天地图地形数据
      tdtMap_imgLayer: null, //天地图影像数据
      // watershed_wmsLayer: null, //流域数据
      // mapClicktag: false, //鼠标点击实践控制标记
      cursor_pointer: true, //鼠标指针样式
      drawVectorLayer: null, //绘制图层
      snapInteraction: null, //吸附控制
      loadStreamTag: false, //河网数据加载标记
      streamLayer: null, //河网图层
      basinBorderLayer: null, //流域边界图层
      basinstreamLayer: null, //水系图层
      subBasinLayers: [], //子流域图层
      subBasinBorderLayers: [], //子流域边界图层
    };
  },
  mounted() {
    // 默认选择背景图层
    this.$refs.layertree.setCheckedKeys([this.checkedId]);
    // 初始化图层
    this.initMap();
  },
  methods: {
    initMap() {
      // 天地图矢量底图
      this.tdtMap_vecLayer = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=vec_w&tk=ba83a5dc9758ca23aea593a39d998825&x={x}&y={y}&l={z}",
        }),
      });
      // 天地图影像底图
      this.tdtMap_imgLayer = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=img_w&tk=ba83a5dc9758ca23aea593a39d998825&x={x}&y={y}&l={z}",
        }),
      });
      // 天地图地形数据
      this.tdtMap_terLayer = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=ter_W&tk=ba83a5dc9758ca23aea593a39d998825&x={x}&y={y}&l={z}",
        }),
      });
      // 天地图矢量注记
      var tdtMap_cva = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=cva_w&tk=ba83a5dc9758ca23aea593a39d998825&x={x}&y={y}&l={z}",
        }),
      });
      // 绘制图层
      this.drawVectorLayer = new VectorLayer({
        source: new VectorSource(),
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),
          stroke: new Stroke({
            color: "Red",
            width: 2,
          }),
          image: new CircleStyle({
            radius: 8,
            fill: new Fill({
              color: "red",
            }),
          }),
        }),
      });

      // wms服务
      var untiled = new Image({
        source: new ImageWMS({
          ratio: 1,
          url: "http://localhost:8050/geoserver/GHFSystemData/wms",
          params: {
            FORMAT: format,
            VERSION: "1.1.1",
            STYLES: "",
            LAYERS: "GHFSystemData:subs1",
            exceptions: "application/vnd.ogc.se_inimage",
          },
        }),
      });

      var wmsSource = new TileWMSSource({
        url: "http://localhost:8050/geoserver/GHFSystemData/wms",
        params: {
          LAYERS: [
            "GHFSystemData:subs1",
            "GHFSystemData:Basin",
            "GHFSystemData:riv1",
            "GHFSystemData:lfp",
            "GHFSystemData:outlets1",
            "GHFSystemData:subbasin_stream",
            // "GHFSystemData:subbasin_upa",
          ],
        },
        serverType: "geoserver",
        crossOrigin: "anonymous",
      });

      // this.watershed_wmsLayer = new TileLayer({
      //   source: wmsSource,
      // });

      const extents = [
        111.99916665866832, 31.00333332931833, 117.48499997005833,
        34.91916664698833,
      ];

      var view = new View({
        projection: "EPSG:4326",
        center: [114.99128966078024, 33.262231628133215],
        zoom: 8,
      });
      this.map = new Map({
        target: "mapDiv",
        logo: false,
        layers: [this.tdtMap_vecLayer, tdtMap_cva, this.drawVectorLayer],
        view: view,
      });

      // 取消双击放大地图
      const dblClickInteraction = this.map
        .getInteractions()
        .getArray()
        .find((interaction) => {
          return interaction instanceof DoubleClickZoom;
        });
      this.map.removeInteraction(dblClickInteraction);
      var _this = this;

      // 鼠标移动显示坐标
      this.map.on("pointermove", function (evt) {
        // var lonlat = proj.transform(evt.coordinate,"EPSG:3857","EPSg:4326");//坐标准换
        _this.lonlat =
          "[ " +
          evt.coordinate[0].toFixed(8) +
          ", " +
          evt.coordinate[1].toFixed(8) +
          " ]";
      });
      // 鼠标点击事件

      this.map.on("singleclick", function (evt) {
        console.log(evt.coordinate);
        // if (_this.mapClicktag) {
        //   // var bound = [
        //   //   117.04212321634216, 27.097216046512514, 117.67373009564338,
        //   //   27.98817560530175,
        //   // ];

        //   // if (_this.isLayerContain(bound, evt.coordinate)) {
        //   //   if (!_this.uniqueLayer(_this.watershed_wmsLayer)) {
        //   //     _this.map.addLayer(_this.watershed_wmsLayer);
        //   //   }
        //   // }
        // } else {
        //   return;
        // }
      });
    },
    // 左侧图层树节点变换检测
    layertreeCheckChange(data, checked, indeterminate) {
      // 获取当前选中节点id
      var checkedArray = this.$refs.layertree.getCheckedKeys();
      if (checked === true) {
        //如果选中节点
        // 如果选中的节点是背景图层，则取消选择上一个背景图层，选择新的图层，即背景图层单选
        if (data.id <= 1.3 && data.id >= 1.1) {
          let backLayerIndex = checkedArray.indexOf(this.backLayersId);
          this.backLayersId = data.id;
          checkedArray.splice(backLayerIndex, 1);
          checkedArray.push(data.id);
        }
        this.checkedId = data.id;
        this.$refs.layertree.setCheckedKeys(checkedArray);

        //图层操作
        switch (data.id) {
          case 1.1:
            if (!this.uniqueLayer(this.tdtMap_vecLayer)) {
              this.map.getLayers().insertAt(0, this.tdtMap_vecLayer);
              // addLayer(this.tdtMap_vecLayer);
            }

            break;
          case 1.2:
            if (!this.uniqueLayer(this.tdtMap_imgLayer)) {
              this.map.getLayers().insertAt(0, this.tdtMap_imgLayer);
              // addLayer(this.tdtMap_vecLayer);
            }

            break;
          case 1.3:
            if (!this.uniqueLayer(this.tdtMap_terLayer)) {
              this.map.getLayers().insertAt(0, this.tdtMap_terLayer);
              // this.map.addLayer(this.tdtMap_terLayer);
            }
            break;
          case 2.1: //河网图层
            // 加载河网图层
            this.loadStreamTag = true;
            break;
          case 2.2:
            // this.mapClicktag = true;
            if (this.basinInitialTag) {
              this.insertLayers(this.basinBorderLayer, -1);
            } else {
              swal({
                title: "请进行流域初始化工作",
                // text: "请输入坐标信息",
                buttons: "确定",
                icon: "error",
              });
            }

            break;
          case 2.3:
            if (this.basinInitialTag) {
              this.map.addLayer(this.basinstreamLayer);
            }

            // this.snapInteraction = new Snap({
            //   source: this.basinstreamLayer.getSource(),
            // });
            break;
          case 2.4:
            if (this.divideSubBasinTag) {
              this.map.addLayer(this.subBasinBorderLayers[0]);
            } else {
              swal({
                title: "子流域尚未划分！",
                // text: "请输入坐标信息",
                buttons: "确定",
                icon: "error",
              });
            }

            break;
          case 2.5:
            if (this.divideSubBasinTag) {
              this.map.addLayer(this.subBasinLayers[0]);
            } else {
              swal({
                title: "子流域尚未划分！",
                // text: "请输入坐标信息",
                buttons: "确定",
                icon: "error",
              });
            }

            break;
          default:
            break;
        }
      } else {
        //如果取消选中节点
        if (this.checkedId == data.id) {
          this.$refs.layertree.setCheckedKeys(checkedArray);
        }
        switch (data.id) {
          case 1.1:
            if (this.uniqueLayer(this.tdtMap_vecLayer)) {
              this.map.removeLayer(this.tdtMap_vecLayer);
            }

            break;

          case 1.2:
            if (this.uniqueLayer(this.tdtMap_imgLayer)) {
              this.map.removeLayer(this.tdtMap_imgLayer);
            }

            break;

          case 1.3:
            if (this.uniqueLayer(this.tdtMap_terLayer)) {
              this.map.removeLayer(this.tdtMap_terLayer);
            }
            break;
          case 2.1:
            this.loadStreamTag = false;
            if (this.uniqueLayer(this.streamLayer)) {
              this.map.removeLayer(this.streamLayer);
            }
            break;
          case 2.2:
            if (this.basinInitialTag) {
              if (this.uniqueLayer(this.basinBorderLayer)) {
                this.map.removeLayer(this.basinBorderLayer);
              }
            }

            break;
          case 2.3:
            if (this.basinInitialTag) {
              if (this.uniqueLayer(this.basinstreamLayer)) {
                this.map.removeLayer(this.basinstreamLayer);
                // this.snapInteraction = null;
              }
            }

            break;
          case 2.4:
            if (this.divideSubBasinTag) {
              if (this.uniqueLayer(this.subBasinBorderLayers[0])) {
                this.map.removeLayer(this.subBasinBorderLayers[0]);
              }
            }

            break;
          case 2.5:
            if (this.divideSubBasinTag) {
              if (this.uniqueLayer(this.subBasinLayers[0])) {
                this.map.removeLayer(this.subBasinLayers[0]);
              }
            }

            break;
          default:
            break;
        }
      }
    },
    // 判断map是否包含当前图层
    uniqueLayer(layer) {
      var mapTileLayers = this.map.getLayers().array_;
      for (let index = 0; index < mapTileLayers.length; index++) {
        const mapLayer = mapTileLayers[index];
        if (layer.ol_uid === mapLayer.ol_uid) {
          return true;
        }
      }
      return false;
    },
    //在特定位置插入图层
    insertLayers(layer, insertIndex) {
      // 插入图层，拓展图层数组
      this.map.addLayer(layer);

      var mapTileLayers = this.map.getLayers().array_;
      const layerCount = mapTileLayers.length;

      // 判断插入位置的合法性
      if (insertIndex < 3) {
        insertIndex = 3;
      } else if (insertIndex >= layerCount) {
        insertIndex = layerCount - 1;
      }

      // 调整图层位置
      for (let index = layerCount - 1; index > insertIndex; index--) {
        mapTileLayers[index] = mapTileLayers[index - 1];
      }
      mapTileLayers[insertIndex] = layer;
    },
    // 解析返回的html数据
    html_parse(strHtml) {
      var parse = new DOMParser();
      var htmlDoc = parse.parseFromString(strHtml, "text/html");
      var tb = htmlDoc.getElementsByClassName("featureInfo")[0];
      if (tb) {
        var rows = tb.rows;
        var tbDataHead = [];
        var tbData = [];
        for (let i = 0; i < rows.length; i++) {
          let cells = rows[i].cells;

          for (let j = 0; j < cells.length; j++) {
            let element = cells[j].innerHTML;
            if (i === 0) {
              tbDataHead.push(element);
            } else {
              tbData.push(element);
            }
          }
        }
        var dicTbData = new Array();
        for (let i = 0; i < tbDataHead.length; i++) {
          dicTbData[tbDataHead[i]] = tbData[i];
        }
        return dicTbData;
      } else {
        return null;
      }
    },
    // 判断当前鼠标是否点在某个流域内
    isLayerContain(bound, currentCoor) {
      // bound:[minlon,minlat,maxlon,maxlat] currentCoor:[lon,lat]
      var minlon, minlat, maxlon, maxlat, lon, lat;
      minlon = bound[0];
      minlat = bound[1];
      maxlon = bound[2];
      maxlat = bound[3];
      lon = currentCoor[0];
      lat = currentCoor[1];
      if (lon >= minlon && lon <= maxlon) {
        if (lat >= minlat && lat <= maxlat) {
          return true;
        }
      }
      return false;
    },
    // 控制顶部菜单详情条显示与否
    menuContainerShow(tag) {
      switch (tag) {
        case 0:
          this.menuContainertag1 = !this.menuContainertag1;
          if (this.menuContainertag2) {
            this.menuContainertag2 = false;
          }
          if (this.menuContainertag3) {
            this.menuContainertag3 = false;
          }
          break;
        case 1:
          this.menuContainertag2 = !this.menuContainertag2;
          if (this.menuContainertag1) {
            this.menuContainertag1 = false;
          }
          if (this.menuContainertag3) {
            this.menuContainertag3 = false;
          }
          break;
        case 2:
          this.menuContainertag3 = !this.menuContainertag3;
          if (this.menuContainertag1) {
            this.menuContainertag1 = false;
          }
          if (this.menuContainertag2) {
            this.menuContainertag2 = false;
          }
          break;
        default:
          break;
      }
    },
    // 漫游
    roaming() {
      console.log("roaming");
    },

    //绘制点
    drawPoint() {
      // 添加绘制交互事件
      // 绘制样式
      //type： 'Point', 'LineString', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection', 'Circle'.
      const pointDraw = new Draw({
        source: this.drawVectorLayer.getSource(),
        type: "Point",
      });
      this.map.addInteraction(pointDraw);
      if (this.snapInteraction) this.map.addInteraction(this.snapInteraction);
      pointDraw.setActive(true);
      pointDraw.on("drawend", (e) => {
        pointDraw.setActive(false);
        let lonlat = e.feature.getGeometry().getCoordinates().splice(",");
        console.log(lonlat[0].toFixed(3));

        this.outlatstationlonlat =
          lonlat[0].toFixed(6) + ", " + lonlat[1].toFixed(6);
      });
    },
    //绘制多边形
    drawPolygon() {
      //type： 'Point', 'LineString', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection', 'Circle'.
      const _this = this;
      const PolygonDraw = new Draw({
        source: this.drawVectorLayer.getSource(),
        type: "Polygon",
      });
      this.map.addInteraction(PolygonDraw);

      PolygonDraw.setActive(true);

      PolygonDraw.on("drawend", (e) => {
        console.log(e);
        PolygonDraw.setActive(false);
        console.log(e.feature.getGeometry().getCoordinates());
      });
    },
    //绘制矩形
    drawBox() {
      const boxDraw = new Draw({
        source: this.drawVectorLayer.getSource(),
        type: "Circle",
        geometryFunction: createBox(),
      });
      this.map.addInteraction(boxDraw);

      boxDraw.setActive(true);

      boxDraw.on("drawend", (e) => {
        boxDraw.setActive(false);
        const boxCoordinates = e.feature.getGeometry().getCoordinates()[0];
        // console.log("绘制要素坐标", boxCoordinates);
        const bbox =
          boxCoordinates[0][0] +
          "," +
          boxCoordinates[0][1] +
          "," +
          boxCoordinates[2][0] +
          "," +
          boxCoordinates[2][1];
        if (this.loadStreamTag) {
          // 添加水系数据
          var streamSource = new VectorSource({
            format: new GeoJSON(),
            url:
              "http://localhost:8050/geoserver/GHFSystemData/ows?service=WFS&version=1.0.0&request=GetFeature&typename=GHFSystemData:huaihestreamshp&outputformat=application/json&bbox=" +
              bbox,
          });
          this.streamLayer = new VectorLayer({
            source: streamSource,
            style: new Style({
              stroke: new Stroke({
                color: "Blue",
                width: 2,
              }),
            }),
          });
          this.map.addLayer(this.streamLayer);
          this.snapInteraction = new Snap({
            source: this.streamLayer.getSource(),
          });

          this.loadStreamTag = false;
        }
      });
    },
    //绘制回退
    rollBack() {
      var drawSource = this.drawVectorLayer.getSource();
      var features = drawSource.getFeatures();
      if (features.length <= 0) {
        console.log("No Draw Features!");
        return 0;
      }
      drawSource.removeFeature(features[features.length - 1]);
      // console.log(drawSource.getFeatures());
    },
    //上传初始化流域数据
    uploadBasBound() {
      var min = this.watershedMinLonLat.split(",");
      var max = this.watershedMaxLonLat.split(",");
      var outlet = this.outletLonLat.split(",");
      console.log(min, max, outlet);
      // if (min == "" || max == "" || outlet == "") {
      //   swal({
      //     title: "输入错误！",
      //     text: "请输入坐标信息",
      //     buttons: "确定",
      //   });
      //   return 0;
      // } else {
      //   if (min.length != 2 || max.length != 2 || outlet.length != 2) {
      //     swal({
      //       title: "格式错误！",
      //       text: "请按照提示格式输入坐标信息",
      //       buttons: "确定",
      //     });
      //   }
      //   return 0;
      // }
      var postData = {
        boundary: {
          xMax: 118.580704716701,
          xMin: 111.955704716701,
          yMax: 34.9041733333333,
          yMin: 30.95834,
        },
        outlet: {
          X: 117.384,
          Y: 32.962,
        },
      };
      // axios
      //   .post("http://localhost:8181/uploadBasBound", postData)
      //   .then((resp) => {
      //     console.log(resp);
      //   });
    },
    //流域初始化
    basinInitial() {
      const _this = this;
      this.basinInitialLoadingTag = !this.basinInitialLoadingTag;
      this.basinInitialbtndisableTag = !this.basinInitialbtndisableTag;
      //  var min = this.watershedMinLonLat.split(",");
      // var max = this.watershedMaxLonLat.split(",");
      // var outlet = this.outletLonLat.split(",");
      // console.log(min, max, outlet);
      // if (min == "" || max == "" || outlet == "") {
      //   swal({
      //     title: "输入错误！",
      //     text: "请输入坐标信息",
      //     buttons: "确定",
      //   });
      //   return 0;
      // } else {
      //   if (min.length != 2 || max.length != 2 || outlet.length != 2) {
      //     swal({
      //       title: "格式错误！",
      //       text: "请按照提示格式输入坐标信息",
      //       buttons: "确定",
      //     });
      //   }
      //   return 0;
      // }
      const fillStyle = new Style({
        fill: new Fill({
          color: "rgba(255, 255, 255, 0.7)",
        }),
        stroke: new Stroke({
          color: "black",
          width: 1,
        }),
      });
      const strokeStyle = new Style({
        stroke: new Stroke({
          color: "blue",
          width: 1,
        }),
      });
      // 111.955704716701,30.95834
      // 118.580704716701,34.9041733333333
      // 117.384,32.962
      var postData = {
        boundary: {
          xMax: 118.580704716701,
          xMin: 111.955704716701,
          yMax: 34.9041733333333,
          yMin: 30.95834,
        },
        outlet: {
          X: 117.384,
          Y: 32.962,
        },
      };
      setTimeout(() => {
        _this.basinInitialLoadingTag = !_this.basinInitialLoadingTag;
        _this.basinInitialbtndisableTag = !_this.basinInitialbtndisableTag;
        _this.watershedIniTag = !_this.watershedIniTag;
        console.log("流域初始化");
        _this.basinstreamLayer = new TileLayer({
          source: new TileWMSSource({
            url: "http://localhost:8050/geoserver/GHFSystemData/wms",
            params: {
              LAYERS: ["GHFSystemData:RstHuaiHeBasinStream"],
            },
            serverType: "geoserver",
            crossOrigin: "anonymous",
          }),
        });
        _this.basinBorderLayer = new TileLayer({
          source: new TileWMSSource({
            url: "http://localhost:8050/geoserver/GHFSystemData/wms",
            params: {
              LAYERS: ["GHFSystemData:basinborder"],
            },
            serverType: "geoserver",
            crossOrigin: "anonymous",
          }),
        });
        _this.basinInitialTag = true;
      }, 3000);

      // axios
      //   .post("http://localhost:8181/basinInitial", postData)
      //   .then((resp) => {
      //     if (resp.data === "OK") {
      //       this.basinInitialLoadingTag = !this.basinInitialLoadingTag;
      //       this.basinInitialbtndisableTag = !this.basinInitialbtndisableTag;
      //       _this.watershedIniTag = !this.watershedIniTag;
      //       console.log("流域初始化");
      //       _this.basinstreamLayer = new VectorLayer({
      //         source: new VectorSource({
      //           url: "http://localhost:8181/static/BasinData/huaihe/stream.json",
      //           format: new GeoJSON(),
      //         }),
      //         style: strokeStyle,
      //       });
      //       _this.basinBorderLayer = new VectorLayer({
      //         source: new VectorSource({
      //           url: "http://localhost:8181/static/BasinData/huaihe/basinborder.json",
      //           format: new GeoJSON(),
      //         }),
      //         style: fillStyle,
      //       });
      //     }
      //   });
    },
    // 子流域划分
    DivideSubBasin() {
      const _this = this;
      this.addOutletLoadingTag = !this.addOutletLoadingTag;
      this.addOutletbtndisableTag = !this.addOutletbtndisableTag;

      setTimeout(() => {
        var subBasinLayer = new TileLayer({
          source: new TileWMSSource({
            url: "http://localhost:8050/geoserver/GHFSystemData/wms",
            params: {
              LAYERS: ["GHFSystemData:Wangjiaba_subBasin"],
            },
            serverType: "geoserver",
            crossOrigin: "anonymous",
          }),
        });

        var subBasinBorderLayer = new TileLayer({
          source: new TileWMSSource({
            url: "http://localhost:8050/geoserver/GHFSystemData/wms",
            params: {
              LAYERS: ["GHFSystemData:Wangjiaba_basinborder"],
            },
            serverType: "geoserver",
            crossOrigin: "anonymous",
          }),
        });

        _this.subBasinLayers.push(subBasinLayer);
        _this.subBasinBorderLayers.push(subBasinBorderLayer);

        _this.divideSubBasinTag = true;

        _this.addOutletTag = !_this.addOutletTag;
        _this.addOutletLoadingTag = !_this.addOutletLoadingTag;
        _this.addOutletbtndisableTag = !_this.addOutletbtndisableTag;
      }, 2000);
    },
  },
};
</script>
<style>
#mapDiv {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
</style>
